Artificial Intelligence Nanodegree

Convolutional Neural Networks

Project: Write an Algorithm for a Dog Identification App


In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested. Sections that begin with '(IMPLEMENTATION)' in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully!

Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a 'Question X' header. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.

The rubric contains optional "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. If you decide to pursue the "Stand Out Suggestions", you should include the code in this IPython notebook.


Why We're Here

In this notebook, you will make the first steps towards developing an algorithm that could be used as part of a mobile or web app. At the end of this project, your code will accept any user-supplied image as input. If a dog is detected in the image, it will provide an estimate of the dog's breed. If a human is detected, it will provide an estimate of the dog breed that is most resembling. The image below displays potential sample output of your finished project (... but we expect that each student's algorithm will behave differently!).

Sample Dog Output

In this real-world setting, you will need to piece together a series of models to perform different tasks; for instance, the algorithm that detects humans in an image will be different from the CNN that infers dog breed. There are many points of possible failure, and no perfect algorithm exists. Your imperfect solution will nonetheless create a fun user experience!

The Road Ahead

We break the notebook into separate steps. Feel free to use the links below to navigate the notebook.

  • Step 0: Import Datasets
  • Step 1: Detect Humans
  • Step 2: Detect Dogs
  • Step 3: Create a CNN to Classify Dog Breeds (from Scratch)
  • Step 4: Use a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 6: Write your Algorithm
  • Step 7: Test Your Algorithm

Step 0: Import Datasets

Import Dog Dataset

In the code cell below, we import a dataset of dog images. We populate a few variables through the use of the load_files function from the scikit-learn library:

  • train_files, valid_files, test_files - numpy arrays containing file paths to images
  • train_targets, valid_targets, test_targets - numpy arrays containing onehot-encoded classification labels
  • dog_names - list of string-valued dog breed names for translating labels
In [1]:
from sklearn.datasets import load_files       
from keras.utils import np_utils
import numpy as np
from glob import glob

# define function to load train, test, and validation datasets
def load_dataset(path):
    data = load_files(path)
    dog_files = np.array(data['filenames'])
    dog_targets = np_utils.to_categorical(np.array(data['target']), 133)
    return dog_files, dog_targets

# load train, test, and validation datasets
train_files, train_targets = load_dataset('dogImages/train')
valid_files, valid_targets = load_dataset('dogImages/valid')
test_files, test_targets = load_dataset('dogImages/test')

# load list of dog names
dog_names = [item[20:-1] for item in sorted(glob("dogImages/train/*/"))]

# print statistics about the dataset
print('There are %d total dog categories.' % len(dog_names))
print('There are %s total dog images.\n' % len(np.hstack([train_files, valid_files, test_files])))
print('There are %d training dog images.' % len(train_files))
print('There are %d validation dog images.' % len(valid_files))
print('There are %d test dog images.'% len(test_files))
Using TensorFlow backend.
There are 133 total dog categories.
There are 8351 total dog images.

There are 6680 training dog images.
There are 835 validation dog images.
There are 836 test dog images.

Import Human Dataset

In the code cell below, we import a dataset of human images, where the file paths are stored in the numpy array human_files.

In [2]:
import random
random.seed(8675309)

# load filenames in shuffled human dataset
human_files = np.array(glob("lfw/*/*"))
random.shuffle(human_files)

# print statistics about the dataset
print('There are %d total human images.' % len(human_files))
There are 13233 total human images.

Step 1: Detect Humans

We use OpenCV's implementation of Haar feature-based cascade classifiers to detect human faces in images. OpenCV provides many pre-trained face detectors, stored as XML files on github. We have downloaded one of these detectors and stored it in the haarcascades directory.

In the next code cell, we demonstrate how to use this detector to find human faces in a sample image.

In [3]:
import cv2                
import matplotlib.pyplot as plt                        
%matplotlib inline                               

# extract pre-trained face detector
face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt.xml')

# load color (BGR) image
img = cv2.imread(human_files[3])
# convert BGR image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# find faces in image
faces = face_cascade.detectMultiScale(gray)

# print number of faces detected in the image
print('Number of faces detected:', len(faces))

# get bounding box for each detected face
for (x,y,w,h) in faces:
    # add bounding box to color image
    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    
# convert BGR image to RGB for plotting
cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# display the image, along with bounding box
plt.imshow(cv_rgb)
plt.show()
Number of faces detected: 1

Before using any of the face detectors, it is standard procedure to convert the images to grayscale. The detectMultiScale function executes the classifier stored in face_cascade and takes the grayscale image as a parameter.

In the above code, faces is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as x and y) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as w and h) specify the width and height of the box.

Write a Human Face Detector

We can use this procedure to write a function that returns True if a human face is detected in an image and False otherwise. This function, aptly named face_detector, takes a string-valued file path to an image as input and appears in the code block below.

In [4]:
# returns "True" if face is detected in image stored at img_path
def face_detector(img_path):
    img = cv2.imread(img_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray)
    return len(faces) > 0

(IMPLEMENTATION) Assess the Human Face Detector

Question 1: Use the code cell below to test the performance of the face_detector function.

  • What percentage of the first 100 images in human_files have a detected human face?
  • What percentage of the first 100 images in dog_files have a detected human face?

Ideally, we would like 100% of human images with a detected face and 0% of dog images with a detected face. You will see that our algorithm falls short of this goal, but still gives acceptable performance. We extract the file paths for the first 100 images from each of the datasets and store them in the numpy arrays human_files_short and dog_files_short.

Answer:

In [5]:
human_files_short = human_files[:100]
dog_files_short = train_files[:100]
# Do NOT modify the code above this line.

## TODO: Test the performance of the face_detector algorithm 
## on the images in human_files_short and dog_files_short.

humans_detected = 0
for img in human_files_short:
    if face_detector(img):
        humans_detected +=1

print('% of first 100 images in human_files that detected a human face: {0:.2f}'.format(humans_detected ))

dogs_detected = 0
dogs_detected_list_haar = []
for i,img in enumerate(dog_files_short):
    if face_detector(img):
        dogs_detected +=1
        dogs_detected_list_haar.append(i)

print('% of first 100 images in dog_files that detected a human face: {0:.2f}'.format(dogs_detected ))
% of first 100 images in human_files that detected a human face: 100.00
% of first 100 images in dog_files that detected a human face: 11.00

Question 2: This algorithmic choice necessitates that we communicate to the user that we accept human images only when they provide a clear view of a face (otherwise, we risk having unneccessarily frustrated users!). In your opinion, is this a reasonable expectation to pose on the user? If not, can you think of a way to detect humans in images that does not necessitate an image with a clearly presented face?

Answer:

We suggest the face detector from OpenCV as a potential way to detect human images in your algorithm, but you are free to explore other approaches, especially approaches that make use of deep learning :). Please use the code cell below to design and test your own face detection algorithm. If you decide to pursue this optional task, report performance on each of the datasets.

Answer: No, in my opinion, it's not reasonable expectation to pose to other. On of the ways to detect humans without such imposition, would be to train the model with additional images that do not have a clear face, so that the model knows how to deal with such images and detect humans in them

In [6]:
## (Optional) TODO: Report the performance of another  
## face detection algorithm on the LFW dataset
### Feel free to use as many code cells as needed.

Using LBP Cascade detection (Answer)

In [7]:
face_cascade2 = cv2.CascadeClassifier('lbpcascade/lbpcascade_frontalcatface.xml')

img = cv2.imread(human_files[3])
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade2.detectMultiScale(gray)
print('Number of faces detected:', len(faces))

for (x,y,w,h) in faces:
    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    
cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

plt.imshow(cv_rgb)
plt.show()
Number of faces detected: 0
In [5]:
# returns "True" if face is detected in image stored at img_path
face_cascade2 = cv2.CascadeClassifier('lbpcascade/lbpcascade_frontalcatface.xml')
def face_detector2(img_path):
    img = cv2.imread(img_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade2.detectMultiScale(gray)
    return len(faces) > 0
In [9]:
human_files_short = human_files[:100]
dog_files_short = train_files[:100]

humans_detected = 0
#list to track detected faces
detected_list = []
for (i,img) in enumerate(human_files_short):
    if face_detector2(img):
        humans_detected +=1
        detected_list.append(i)

print('% of first 100 images in human_files that detected a human face: {0:.2f}'.format(humans_detected ))

dogs_detected = 0
dogs_detected_list = []
for (i,img) in enumerate(dog_files_short):
    if face_detector2(img):
        dogs_detected +=1
        dogs_detected_list.append(i)

print('% of first 100 images in dog_files that detected a human face: {0:.2f}'.format(dogs_detected ))
% of first 100 images in human_files that detected a human face: 6.00
% of first 100 images in dog_files that detected a human face: 6.00
In [10]:
print(detected_list)
print(dogs_detected_list)
print(dogs_detected_list_haar)
[7, 10, 15, 19, 59, 74]
[0, 30, 57, 59, 65, 78]
[0, 14, 15, 21, 22, 23, 24, 30, 32, 63, 78]
In [5]:
def display_detected(detector, idx_list, files):
    plt.figure(figsize=(20,6))
    for ind,i in enumerate(idx_list):
        img = cv2.imread(files[i])
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        faces = detector.detectMultiScale(gray)

        for (x,y,w,h) in faces:
            cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),5)

        cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

        plt.subplot(1,6,ind+1)
        plt.imshow(cv_rgb)
#         plt.show()
In [12]:
display_detected(face_cascade2, detected_list, human_files_short)
In [13]:
display_detected(face_cascade2, dogs_detected_list, dog_files_short)
In [14]:
display_detected(face_cascade, dogs_detected_list_haar[:6], dog_files_short)
In [15]:
display_detected(face_cascade, dogs_detected_list_haar[6:], dog_files_short)
In [ ]:
 

Step 2: Detect Dogs

In this section, we use a pre-trained ResNet-50 model to detect dogs in images. Our first line of code downloads the ResNet-50 model, along with weights that have been trained on ImageNet, a very large, very popular dataset used for image classification and other vision tasks. ImageNet contains over 10 million URLs, each linking to an image containing an object from one of 1000 categories. Given an image, this pre-trained ResNet-50 model returns a prediction (derived from the available categories in ImageNet) for the object that is contained in the image.

In [6]:
from keras.applications.resnet50 import ResNet50

# define ResNet50 model
ResNet50_model = ResNet50(weights='imagenet')

Pre-process the Data

When using TensorFlow as backend, Keras CNNs require a 4D array (which we'll also refer to as a 4D tensor) as input, with shape

$$ (\text{nb_samples}, \text{rows}, \text{columns}, \text{channels}), $$

where nb_samples corresponds to the total number of images (or samples), and rows, columns, and channels correspond to the number of rows, columns, and channels for each image, respectively.

The path_to_tensor function below takes a string-valued file path to a color image as input and returns a 4D tensor suitable for supplying to a Keras CNN. The function first loads the image and resizes it to a square image that is $224 \times 224$ pixels. Next, the image is converted to an array, which is then resized to a 4D tensor. In this case, since we are working with color images, each image has three channels. Likewise, since we are processing a single image (or sample), the returned tensor will always have shape

$$ (1, 224, 224, 3). $$

The paths_to_tensor function takes a numpy array of string-valued image paths as input and returns a 4D tensor with shape

$$ (\text{nb_samples}, 224, 224, 3). $$

Here, nb_samples is the number of samples, or number of images, in the supplied array of image paths. It is best to think of nb_samples as the number of 3D tensors (where each 3D tensor corresponds to a different image) in your dataset!

In [7]:
from keras.preprocessing import image                  
from tqdm import tqdm

def path_to_tensor(img_path):
    # loads RGB image as PIL.Image.Image type
    img = image.load_img(img_path, target_size=(224, 224))
    # convert PIL.Image.Image type to 3D tensor with shape (224, 224, 3)
    x = image.img_to_array(img)
    # convert 3D tensor to 4D tensor with shape (1, 224, 224, 3) and return 4D tensor
    return np.expand_dims(x, axis=0)

def paths_to_tensor(img_paths):
    list_of_tensors = [path_to_tensor(img_path) for img_path in tqdm(img_paths)]
    return np.vstack(list_of_tensors)

Making Predictions with ResNet-50

Getting the 4D tensor ready for ResNet-50, and for any other pre-trained model in Keras, requires some additional processing. First, the RGB image is converted to BGR by reordering the channels. All pre-trained models have the additional normalization step that the mean pixel (expressed in RGB as $[103.939, 116.779, 123.68]$ and calculated from all pixels in all images in ImageNet) must be subtracted from every pixel in each image. This is implemented in the imported function preprocess_input. If you're curious, you can check the code for preprocess_input here.

Now that we have a way to format our image for supplying to ResNet-50, we are now ready to use the model to extract the predictions. This is accomplished with the predict method, which returns an array whose $i$-th entry is the model's predicted probability that the image belongs to the $i$-th ImageNet category. This is implemented in the ResNet50_predict_labels function below.

By taking the argmax of the predicted probability vector, we obtain an integer corresponding to the model's predicted object class, which we can identify with an object category through the use of this dictionary.

In [8]:
from keras.applications.resnet50 import preprocess_input, decode_predictions

def ResNet50_predict_labels(img_path):
    # returns prediction vector for image located at img_path
    img = preprocess_input(path_to_tensor(img_path))
    return np.argmax(ResNet50_model.predict(img))

Write a Dog Detector

While looking at the dictionary, you will notice that the categories corresponding to dogs appear in an uninterrupted sequence and correspond to dictionary keys 151-268, inclusive, to include all categories from 'Chihuahua' to 'Mexican hairless'. Thus, in order to check to see if an image is predicted to contain a dog by the pre-trained ResNet-50 model, we need only check if the ResNet50_predict_labels function above returns a value between 151 and 268 (inclusive).

We use these ideas to complete the dog_detector function below, which returns True if a dog is detected in an image (and False if not).

In [9]:
### returns "True" if a dog is detected in the image stored at img_path
def dog_detector(img_path):
    prediction = ResNet50_predict_labels(img_path)
    return ((prediction <= 268) & (prediction >= 151)) 

(IMPLEMENTATION) Assess the Dog Detector

Question 3: Use the code cell below to test the performance of your dog_detector function.

  • What percentage of the images in human_files_short have a detected dog?
  • What percentage of the images in dog_files_short have a detected dog?

Answer:

In [20]:
### TODO: Test the performance of the dog_detector function
### on the images in human_files_short and dog_files_short.

humans_detected = 0
humans_detected_list_resnet = []
for (i,img) in enumerate(human_files_short):
    if dog_detector(img):
        humans_detected +=1
        humans_detected_list_resnet.append(i)

print('% of first 100 images in human_files_short that detected a dog face: {0:.2f}'.format(humans_detected ))

dogs_detected = 0
dogs_detected_list_resnet = []
for (i,img) in enumerate(dog_files_short):
    if dog_detector(img):
        dogs_detected +=1
        dogs_detected_list_resnet.append(i)
        
print('% of first 100 images in dog_files_short that detected a dog face: {0:.2f}'.format(dogs_detected ))
% of first 100 images in human_files_short that detected a dog face: 0.00
% of first 100 images in dog_files_short that detected a dog face: 100.00

Step 3: Create a CNN to Classify Dog Breeds (from Scratch)

Now that we have functions for detecting humans and dogs in images, we need a way to predict breed from images. In this step, you will create a CNN that classifies dog breeds. You must create your CNN from scratch (so, you can't use transfer learning yet!), and you must attain a test accuracy of at least 1%. In Step 5 of this notebook, you will have the opportunity to use transfer learning to create a CNN that attains greatly improved accuracy.

Be careful with adding too many trainable layers! More parameters means longer training, which means you are more likely to need a GPU to accelerate the training process. Thankfully, Keras provides a handy estimate of the time that each epoch is likely to take; you can extrapolate this estimate to figure out how long it will take for your algorithm to train.

We mention that the task of assigning breed to dogs from images is considered exceptionally challenging. To see why, consider that even a human would have great difficulty in distinguishing between a Brittany and a Welsh Springer Spaniel.

Brittany Welsh Springer Spaniel

It is not difficult to find other dog breed pairs with minimal inter-class variation (for instance, Curly-Coated Retrievers and American Water Spaniels).

Curly-Coated Retriever American Water Spaniel

Likewise, recall that labradors come in yellow, chocolate, and black. Your vision-based algorithm will have to conquer this high intra-class variation to determine how to classify all of these different shades as the same breed.

Yellow Labrador Chocolate Labrador Black Labrador

We also mention that random chance presents an exceptionally low bar: setting aside the fact that the classes are slightly imabalanced, a random guess will provide a correct answer roughly 1 in 133 times, which corresponds to an accuracy of less than 1%.

Remember that the practice is far ahead of the theory in deep learning. Experiment with many different architectures, and trust your intuition. And, of course, have fun!

Pre-process the Data

We rescale the images by dividing every pixel in every image by 255.

In [10]:
from PIL import ImageFile                            
ImageFile.LOAD_TRUNCATED_IMAGES = True                 

# pre-process the data for Keras
train_tensors = paths_to_tensor(train_files).astype('float32')/255
valid_tensors = paths_to_tensor(valid_files).astype('float32')/255
test_tensors = paths_to_tensor(test_files).astype('float32')/255
100%|██████████| 6680/6680 [02:02<00:00, 54.35it/s]
100%|██████████| 835/835 [00:14<00:00, 58.49it/s]
100%|██████████| 836/836 [00:13<00:00, 60.67it/s]

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:

    model.summary()

We have imported some Python modules to get you started, but feel free to import as many modules as you need. If you end up getting stuck, here's a hint that specifies a model that trains relatively fast on CPU and attains >1% test accuracy in 5 epochs:

Sample CNN

Question 4: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. If you chose to use the hinted architecture above, describe why you think that CNN architecture should work well for the image classification task.

Answer:

Answer: I chose to use the hinted architecture above as against MLP because of mainly 2 reasons:

  1. The MLPs use a lot of parameters, and hence might be difficult to run them efficiently
  2. They lose the information contained in the nearby pixels when we flatten them

CNNs easily overcome these 2 drawbacks. Hence I chose to Use CNN. Further, I chose each of the layers due to following reason to overcome the above drawbacks:

  1. Convolutional layer uses the local connectivity information to detect patterns in small regions in the images based on the filter size. Here, we try to increase the depth of the arrays.
  2. I tried following each conv layer with Maxpooling layer, in order to decrease the height and width of the imafe representation arrays, so as to reduce the number of parameters.
In [13]:
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.layers import Dropout, Flatten, Dense
from keras.models import Sequential

model = Sequential()

### TODO: Define your architecture.
model.add(Conv2D(filters=16, kernel_size=(2,2), strides=1, padding='valid', activation='relu', input_shape=(224,224,3)))
model.add(MaxPooling2D(pool_size=(2,2), strides=2, padding='valid'))
model.add(Conv2D(filters=32, kernel_size=(2,2), strides=1, padding='valid', activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2), strides=2, padding='valid'))
model.add(Conv2D(filters=64, kernel_size=(2,2), strides=1, padding='valid', activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2), strides=2, padding='valid'))
model.add(GlobalAveragePooling2D())
model.add(Dense(133, activation='softmax'))

model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_1 (Conv2D)            (None, 223, 223, 16)      208       
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 111, 111, 16)      0         
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 110, 110, 32)      2080      
_________________________________________________________________
max_pooling2d_3 (MaxPooling2 (None, 55, 55, 32)        0         
_________________________________________________________________
conv2d_3 (Conv2D)            (None, 54, 54, 64)        8256      
_________________________________________________________________
max_pooling2d_4 (MaxPooling2 (None, 27, 27, 64)        0         
_________________________________________________________________
global_average_pooling2d_1 ( (None, 64)                0         
_________________________________________________________________
dense_1 (Dense)              (None, 133)               8645      
=================================================================
Total params: 19,189.0
Trainable params: 19,189.0
Non-trainable params: 0.0
_________________________________________________________________

Compile the Model

In [14]:
model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])

(IMPLEMENTATION) Train the Model

Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.

You are welcome to augment the training data, but this is not a requirement.

In [15]:
from keras.callbacks import ModelCheckpoint  

### TODO: specify the number of epochs that you would like to use to train the model.

epochs = 5

### Do NOT modify the code below this line.

checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.from_scratch.hdf5', 
                               verbose=1, save_best_only=True)

model.fit(train_tensors, train_targets, 
          validation_data=(valid_tensors, valid_targets),
          epochs=epochs, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/5
6660/6680 [============================>.] - ETA: 0s - loss: 4.8826 - acc: 0.0093  Epoch 00000: val_loss improved from inf to 4.86732, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 161s - loss: 4.8824 - acc: 0.0093 - val_loss: 4.8673 - val_acc: 0.0132
Epoch 2/5
6660/6680 [============================>.] - ETA: 0s - loss: 4.8461 - acc: 0.0161      Epoch 00001: val_loss improved from 4.86732 to 4.82752, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 157s - loss: 4.8461 - acc: 0.0160 - val_loss: 4.8275 - val_acc: 0.0168
Epoch 3/5
6660/6680 [============================>.] - ETA: 0s - loss: 4.7957 - acc: 0.0191      Epoch 00002: val_loss improved from 4.82752 to 4.79488, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 171s - loss: 4.7957 - acc: 0.0190 - val_loss: 4.7949 - val_acc: 0.0228
Epoch 4/5
6660/6680 [============================>.] - ETA: 0s - loss: 4.7576 - acc: 0.0195  Epoch 00003: val_loss improved from 4.79488 to 4.77345, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 186s - loss: 4.7574 - acc: 0.0196 - val_loss: 4.7734 - val_acc: 0.0204
Epoch 5/5
6660/6680 [============================>.] - ETA: 0s - loss: 4.7314 - acc: 0.0209  Epoch 00004: val_loss improved from 4.77345 to 4.75399, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 172s - loss: 4.7312 - acc: 0.0208 - val_loss: 4.7540 - val_acc: 0.0204
Out[15]:
<keras.callbacks.History at 0x125963908>

Load the Model with the Best Validation Loss

In [16]:
model.load_weights('saved_models/weights.best.from_scratch.hdf5')

Test the Model

Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 1%.

In [17]:
# get index of predicted dog breed for each image in test set
dog_breed_predictions = [np.argmax(model.predict(np.expand_dims(tensor, axis=0))) for tensor in test_tensors]

# report test accuracy
test_accuracy = 100*np.sum(np.array(dog_breed_predictions)==np.argmax(test_targets, axis=1))/len(dog_breed_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 2.6316%

Step 4: Use a CNN to Classify Dog Breeds

To reduce training time without sacrificing accuracy, we show you how to train a CNN using transfer learning. In the following step, you will get a chance to use transfer learning to train your own CNN.

Obtain Bottleneck Features

In [22]:
bottleneck_features = np.load('bottleneck_features/DogVGG16Data.npz')
train_VGG16 = bottleneck_features['train']
valid_VGG16 = bottleneck_features['valid']
test_VGG16 = bottleneck_features['test']

Model Architecture

The model uses the the pre-trained VGG-16 model as a fixed feature extractor, where the last convolutional output of VGG-16 is fed as input to our model. We only add a global average pooling layer and a fully connected layer, where the latter contains one node for each dog category and is equipped with a softmax.

In [24]:
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.layers import Dropout, Flatten, Dense
from keras.models import Sequential

VGG16_model = Sequential()
VGG16_model.add(GlobalAveragePooling2D(input_shape=train_VGG16.shape[1:]))
VGG16_model.add(Dense(133, activation='softmax'))

VGG16_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_1 ( (None, 512)               0         
_________________________________________________________________
dense_1 (Dense)              (None, 133)               68229     
=================================================================
Total params: 68,229.0
Trainable params: 68,229.0
Non-trainable params: 0.0
_________________________________________________________________

Compile the Model

In [25]:
VGG16_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

Train the Model

In [27]:
import keras
from keras.callbacks import ModelCheckpoint

checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.VGG16.hdf5', 
                               verbose=1, save_best_only=True)

VGG16_model.fit(train_VGG16, train_targets, 
          validation_data=(valid_VGG16, valid_targets),
          epochs=20, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6440/6680 [===========================>..] - ETA: 0s - loss: 12.3626 - acc: 0.1233      Epoch 00000: val_loss improved from inf to 11.01514, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 12.3113 - acc: 0.1263 - val_loss: 11.0151 - val_acc: 0.2180
Epoch 2/20
6660/6680 [============================>.] - ETA: 0s - loss: 10.5423 - acc: 0.2718Epoch 00001: val_loss improved from 11.01514 to 10.38132, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 10.5446 - acc: 0.2719 - val_loss: 10.3813 - val_acc: 0.2778
Epoch 3/20
6640/6680 [============================>.] - ETA: 0s - loss: 10.1439 - acc: 0.3203Epoch 00002: val_loss improved from 10.38132 to 10.26089, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 10.1578 - acc: 0.3198 - val_loss: 10.2609 - val_acc: 0.2970
Epoch 4/20
6500/6680 [============================>.] - ETA: 0s - loss: 9.8681 - acc: 0.3485 Epoch 00003: val_loss improved from 10.26089 to 9.92142, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 9.8571 - acc: 0.3491 - val_loss: 9.9214 - val_acc: 0.3317
Epoch 5/20
6500/6680 [============================>.] - ETA: 0s - loss: 9.6511 - acc: 0.3706 Epoch 00004: val_loss improved from 9.92142 to 9.91244, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 9.6321 - acc: 0.3714 - val_loss: 9.9124 - val_acc: 0.3305
Epoch 6/20
6500/6680 [============================>.] - ETA: 0s - loss: 9.4848 - acc: 0.3868 Epoch 00005: val_loss improved from 9.91244 to 9.81669, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 9.4639 - acc: 0.3879 - val_loss: 9.8167 - val_acc: 0.3246
Epoch 7/20
6660/6680 [============================>.] - ETA: 0s - loss: 9.3416 - acc: 0.4006Epoch 00006: val_loss improved from 9.81669 to 9.67601, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 9.3529 - acc: 0.3999 - val_loss: 9.6760 - val_acc: 0.3413
Epoch 8/20
6480/6680 [============================>.] - ETA: 0s - loss: 9.0783 - acc: 0.4093 Epoch 00007: val_loss improved from 9.67601 to 9.38041, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 9.0908 - acc: 0.4082 - val_loss: 9.3804 - val_acc: 0.3485
Epoch 9/20
6660/6680 [============================>.] - ETA: 0s - loss: 8.6864 - acc: 0.4317Epoch 00008: val_loss improved from 9.38041 to 9.02959, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 8.6814 - acc: 0.4317 - val_loss: 9.0296 - val_acc: 0.3713
Epoch 10/20
6600/6680 [============================>.] - ETA: 0s - loss: 8.4034 - acc: 0.4544 Epoch 00009: val_loss improved from 9.02959 to 8.70286, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 8.3942 - acc: 0.4548 - val_loss: 8.7029 - val_acc: 0.3976
Epoch 11/20
6540/6680 [============================>.] - ETA: 0s - loss: 8.2994 - acc: 0.4683Epoch 00010: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 8.3143 - acc: 0.4677 - val_loss: 8.7642 - val_acc: 0.3964
Epoch 12/20
6440/6680 [===========================>..] - ETA: 0s - loss: 8.2375 - acc: 0.4744Epoch 00011: val_loss improved from 8.70286 to 8.67019, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 8.2504 - acc: 0.4735 - val_loss: 8.6702 - val_acc: 0.3952
Epoch 13/20
6460/6680 [============================>.] - ETA: 0s - loss: 8.0068 - acc: 0.4802Epoch 00012: val_loss improved from 8.67019 to 8.46335, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 8.0114 - acc: 0.4796 - val_loss: 8.4633 - val_acc: 0.4072
Epoch 14/20
6600/6680 [============================>.] - ETA: 0s - loss: 7.7882 - acc: 0.4974Epoch 00013: val_loss improved from 8.46335 to 8.34838, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 7.7970 - acc: 0.4967 - val_loss: 8.3484 - val_acc: 0.4084
Epoch 15/20
6620/6680 [============================>.] - ETA: 0s - loss: 7.6751 - acc: 0.5103Epoch 00014: val_loss improved from 8.34838 to 8.25839, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 7.6679 - acc: 0.5106 - val_loss: 8.2584 - val_acc: 0.4120
Epoch 16/20
6420/6680 [===========================>..] - ETA: 0s - loss: 7.4774 - acc: 0.5237Epoch 00015: val_loss improved from 8.25839 to 8.02297, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 7.4877 - acc: 0.5234 - val_loss: 8.0230 - val_acc: 0.4443
Epoch 17/20
6500/6680 [============================>.] - ETA: 0s - loss: 7.3545 - acc: 0.5323Epoch 00016: val_loss improved from 8.02297 to 7.87313, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 7.3549 - acc: 0.5323 - val_loss: 7.8731 - val_acc: 0.4491
Epoch 18/20
6540/6680 [============================>.] - ETA: 0s - loss: 7.3104 - acc: 0.5391Epoch 00017: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 7.3103 - acc: 0.5392 - val_loss: 7.9067 - val_acc: 0.4419
Epoch 19/20
6500/6680 [============================>.] - ETA: 0s - loss: 7.1574 - acc: 0.5415Epoch 00018: val_loss improved from 7.87313 to 7.80723, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 7.1681 - acc: 0.5409 - val_loss: 7.8072 - val_acc: 0.4467
Epoch 20/20
6360/6680 [===========================>..] - ETA: 0s - loss: 7.0703 - acc: 0.5505 Epoch 00019: val_loss improved from 7.80723 to 7.70104, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 7.0660 - acc: 0.5506 - val_loss: 7.7010 - val_acc: 0.4575
Out[27]:
<keras.callbacks.History at 0x12131f1d0>

Load the Model with the Best Validation Loss

In [28]:
VGG16_model.load_weights('saved_models/weights.best.VGG16.hdf5')

Test the Model

Now, we can use the CNN to test how well it identifies breed within our test dataset of dog images. We print the test accuracy below.

In [29]:
# get index of predicted dog breed for each image in test set
VGG16_predictions = [np.argmax(VGG16_model.predict(np.expand_dims(feature, axis=0))) for feature in test_VGG16]

# report test accuracy
test_accuracy = 100*np.sum(np.array(VGG16_predictions)==np.argmax(test_targets, axis=1))/len(VGG16_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 45.0957%

Predict Dog Breed with the Model

In [30]:
from extract_bottleneck_features import *

def VGG16_predict_breed(img_path):
    # extract bottleneck features
    bottleneck_feature = extract_VGG16(path_to_tensor(img_path))
    # obtain predicted vector
    predicted_vector = VGG16_model.predict(bottleneck_feature)
    # return dog breed that is predicted by the model
    return dog_names[np.argmax(predicted_vector)]

Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)

You will now use transfer learning to create a CNN that can identify dog breed from images. Your CNN must attain at least 60% accuracy on the test set.

In Step 4, we used transfer learning to create a CNN using VGG-16 bottleneck features. In this section, you must use the bottleneck features from a different pre-trained model. To make things easier for you, we have pre-computed the features for all of the networks that are currently available in Keras:

The files are encoded as such:

Dog{network}Data.npz

where {network}, in the above filename, can be one of VGG19, Resnet50, InceptionV3, or Xception. Pick one of the above architectures, download the corresponding bottleneck features, and store the downloaded file in the bottleneck_features/ folder in the repository.

(IMPLEMENTATION) Obtain Bottleneck Features

In the code block below, extract the bottleneck features corresponding to the train, test, and validation sets by running the following:

bottleneck_features = np.load('bottleneck_features/Dog{network}Data.npz')
train_{network} = bottleneck_features['train']
valid_{network} = bottleneck_features['valid']
test_{network} = bottleneck_features['test']
In [11]:
### TODO: Obtain bottleneck features from another pre-trained CNN.

#VGG19

bottleneck_features2 = np.load('bottleneck_features/DogVGG19Data.npz')

train_VGG119 = bottleneck_features2['train']
test_VGG19 = bottleneck_features2['test']
valid_VGG19 = bottleneck_features2['valid']
In [12]:
train_VGG119.shape
Out[12]:
(6680, 7, 7, 512)
In [13]:
### TODO: Obtain bottleneck features from another pre-trained CNN.

#ResNet50

bottleneck_features3 = np.load('bottleneck_features/DogResnet50Data.npz')

train_ResNet50 = bottleneck_features3['train']
test_ResNet50 = bottleneck_features3['test']
valid_ResNet50 = bottleneck_features3['valid']
In [14]:
train_ResNet50.shape
Out[14]:
(6680, 1, 1, 2048)
In [15]:
### TODO: Obtain bottleneck features from another pre-trained CNN.

#Inception

bottleneck_features4 = np.load('bottleneck_features/DogInceptionV3Data.npz')

train_Inception = bottleneck_features4['train']
test_Inception = bottleneck_features4['test']
valid_Inception = bottleneck_features4['valid']
In [16]:
train_Inception.shape
Out[16]:
(6680, 5, 5, 2048)
In [17]:
### TODO: Obtain bottleneck features from another pre-trained CNN.

#Xception

bottleneck_features5 = np.load('bottleneck_features/DogXceptionData.npz')

train_Xception = bottleneck_features5['train']
test_Xception = bottleneck_features5['test']
valid_Xception = bottleneck_features5['valid']
In [18]:
train_Xception.shape
Out[18]:
(6680, 7, 7, 2048)

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:

    <your model's name>.summary()

Question 5: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. Describe why you think the architecture is suitable for the current problem.

Answer:

Answer: The CNN model from scratch that we tried above gave a 2.6% accuracy, which is greater than probablity taht everything belonged to a single class (1/133*100 = .75%). Hence we can conclude that CNNs are working, we just need to improve it. In addition, the current problem images images are similar to those in ImageNet database, hence, we can re-use one of the existing trained models. I first tried VGG19 model, but it seemed to give just about 60% accuracy. Based on this, I tried to train and test multiple architechtures here, and found that the architechture using Xception model for transfer learning gives the highest accuracy. Hence I think the architecture using the weights from the Xception model seems suitable

Answer: I used the VGG19 existing model, since our dataset (dogs) is small and is similar to the Image Net dataset. As in transfer leraning, I pretrain the data using the existing model to train foir simpler things like detecting edges, shapes and other common features. Then I add Global Average Pooling layer, instead of just Flatten and Dense layer, the number of parameters would have been way higher. Now the nuber of parameters are about 70K. Then I use a fuly connected layer to get the output, where 133 represents the no of classes (dog breeds) and I use softmax, as the output probability has to be between 0 & 1

In [19]:
### TODO: Define your architecture.

from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.layers import Dropout, Flatten, Dense
from keras.models import Sequential

VGG19_model = Sequential()
VGG19_model.add(GlobalAveragePooling2D(input_shape=(7, 7, 512)))
VGG19_model.add(Dense(133, activation='softmax'))
VGG19_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_1 ( (None, 512)               0         
_________________________________________________________________
dense_1 (Dense)              (None, 133)               68229     
=================================================================
Total params: 68,229.0
Trainable params: 68,229.0
Non-trainable params: 0.0
_________________________________________________________________
In [20]:
### TODO: Define your architecture.
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.layers import Dropout, Flatten, Dense
from keras.models import Sequential


ResNet50_model2 = Sequential()
ResNet50_model2.add(GlobalAveragePooling2D(input_shape=(1, 1, 2048)))
ResNet50_model2.add(Dense(133, activation='softmax'))
ResNet50_model2.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_2 ( (None, 2048)              0         
_________________________________________________________________
dense_2 (Dense)              (None, 133)               272517    
=================================================================
Total params: 272,517.0
Trainable params: 272,517.0
Non-trainable params: 0.0
_________________________________________________________________
In [21]:
### TODO: Define your architecture.
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.layers import Dropout, Flatten, Dense
from keras.models import Sequential

Inception_model = Sequential()
Inception_model.add(GlobalAveragePooling2D(input_shape=(5, 5, 2048)))
Inception_model.add(Dense(133, activation='softmax'))
Inception_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_3 ( (None, 2048)              0         
_________________________________________________________________
dense_3 (Dense)              (None, 133)               272517    
=================================================================
Total params: 272,517.0
Trainable params: 272,517.0
Non-trainable params: 0.0
_________________________________________________________________
In [22]:
### TODO: Define your architecture.
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.layers import Dropout, Flatten, Dense
from keras.models import Sequential

Xception_model = Sequential()
Xception_model.add(GlobalAveragePooling2D(input_shape=( 7, 7, 2048)))
Xception_model.add(Dense(133, activation='softmax'))
Xception_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_4 ( (None, 2048)              0         
_________________________________________________________________
dense_4 (Dense)              (None, 133)               272517    
=================================================================
Total params: 272,517.0
Trainable params: 272,517.0
Non-trainable params: 0.0
_________________________________________________________________

(IMPLEMENTATION) Compile the Model

In [23]:
### TODO: Compile the model.
VGG19_model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])
In [24]:
### TODO: Compile the model.
ResNet50_model2.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])
In [25]:
### TODO: Compile the model.
Inception_model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])
In [26]:
### TODO: Compile the model.
Xception_model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])

(IMPLEMENTATION) Train the Model

Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.

You are welcome to augment the training data, but this is not a requirement.

In [47]:
### TODO: Train the model.

import keras
from keras.callbacks import ModelCheckpoint

checkpointer19 = ModelCheckpoint(filepath='dogvgg19.weights.best.mine.hdf5', verbose=1, save_best_only=True)

hist2 = VGG19_model.fit(train_VGG119, train_targets, callbacks=[checkpointer19], epochs=100,
                       verbose=2, validation_data=(valid_VGG19, valid_targets), shuffle=True)
Train on 6680 samples, validate on 835 samples
Epoch 1/100
Epoch 00000: val_loss improved from inf to 9.95784, saving model to dogvgg19.weights.best.mine.hdf5
2s - loss: 11.8782 - acc: 0.1229 - val_loss: 9.9578 - val_acc: 0.2144
Epoch 2/100
Epoch 00001: val_loss improved from 9.95784 to 9.11454, saving model to dogvgg19.weights.best.mine.hdf5
0s - loss: 9.1753 - acc: 0.3190 - val_loss: 9.1145 - val_acc: 0.3174
Epoch 3/100
Epoch 00002: val_loss improved from 9.11454 to 8.82082, saving model to dogvgg19.weights.best.mine.hdf5
0s - loss: 8.5787 - acc: 0.3961 - val_loss: 8.8208 - val_acc: 0.3545
Epoch 4/100
Epoch 00003: val_loss improved from 8.82082 to 8.59573, saving model to dogvgg19.weights.best.mine.hdf5
0s - loss: 8.2445 - acc: 0.4332 - val_loss: 8.5957 - val_acc: 0.3868
Epoch 5/100
Epoch 00004: val_loss improved from 8.59573 to 8.50812, saving model to dogvgg19.weights.best.mine.hdf5
0s - loss: 8.0288 - acc: 0.4612 - val_loss: 8.5081 - val_acc: 0.3808
Epoch 6/100
Epoch 00005: val_loss improved from 8.50812 to 8.40673, saving model to dogvgg19.weights.best.mine.hdf5
0s - loss: 7.8749 - acc: 0.4798 - val_loss: 8.4067 - val_acc: 0.3928
Epoch 7/100
Epoch 00006: val_loss improved from 8.40673 to 8.17747, saving model to dogvgg19.weights.best.mine.hdf5
0s - loss: 7.6663 - acc: 0.4990 - val_loss: 8.1775 - val_acc: 0.4084
Epoch 8/100
Epoch 00007: val_loss did not improve
0s - loss: 7.6103 - acc: 0.5135 - val_loss: 8.2364 - val_acc: 0.4084
Epoch 9/100
Epoch 00008: val_loss improved from 8.17747 to 7.99538, saving model to dogvgg19.weights.best.mine.hdf5
0s - loss: 7.5053 - acc: 0.5183 - val_loss: 7.9954 - val_acc: 0.4299
Epoch 10/100
Epoch 00009: val_loss did not improve
0s - loss: 7.4325 - acc: 0.5281 - val_loss: 8.0118 - val_acc: 0.4431
Epoch 11/100
Epoch 00010: val_loss improved from 7.99538 to 7.94608, saving model to dogvgg19.weights.best.mine.hdf5
0s - loss: 7.4163 - acc: 0.5322 - val_loss: 7.9461 - val_acc: 0.4359
Epoch 12/100
Epoch 00011: val_loss improved from 7.94608 to 7.85292, saving model to dogvgg19.weights.best.mine.hdf5
0s - loss: 7.3213 - acc: 0.5368 - val_loss: 7.8529 - val_acc: 0.4455
Epoch 13/100
Epoch 00012: val_loss did not improve
0s - loss: 7.2969 - acc: 0.5406 - val_loss: 7.9070 - val_acc: 0.4479
Epoch 14/100
Epoch 00013: val_loss did not improve
0s - loss: 7.2827 - acc: 0.5428 - val_loss: 7.8643 - val_acc: 0.4503
Epoch 15/100
Epoch 00014: val_loss improved from 7.85292 to 7.76775, saving model to dogvgg19.weights.best.mine.hdf5
0s - loss: 7.1752 - acc: 0.5460 - val_loss: 7.7678 - val_acc: 0.4491
Epoch 16/100
Epoch 00015: val_loss did not improve
0s - loss: 7.1384 - acc: 0.5524 - val_loss: 7.8197 - val_acc: 0.4455
Epoch 17/100
Epoch 00016: val_loss improved from 7.76775 to 7.47075, saving model to dogvgg19.weights.best.mine.hdf5
0s - loss: 6.9675 - acc: 0.5515 - val_loss: 7.4708 - val_acc: 0.4635
Epoch 18/100
Epoch 00017: val_loss did not improve
0s - loss: 6.8125 - acc: 0.5677 - val_loss: 7.4897 - val_acc: 0.4659
Epoch 19/100
Epoch 00018: val_loss improved from 7.47075 to 7.46147, saving model to dogvgg19.weights.best.mine.hdf5
0s - loss: 6.7913 - acc: 0.5735 - val_loss: 7.4615 - val_acc: 0.4599
Epoch 20/100
Epoch 00019: val_loss improved from 7.46147 to 7.42654, saving model to dogvgg19.weights.best.mine.hdf5
0s - loss: 6.7788 - acc: 0.5747 - val_loss: 7.4265 - val_acc: 0.4766
Epoch 21/100
Epoch 00020: val_loss improved from 7.42654 to 7.37415, saving model to dogvgg19.weights.best.mine.hdf5
0s - loss: 6.7060 - acc: 0.5768 - val_loss: 7.3742 - val_acc: 0.4814
Epoch 22/100
Epoch 00021: val_loss improved from 7.37415 to 7.34216, saving model to dogvgg19.weights.best.mine.hdf5
0s - loss: 6.6461 - acc: 0.5837 - val_loss: 7.3422 - val_acc: 0.4826
Epoch 23/100
Epoch 00022: val_loss improved from 7.34216 to 7.28480, saving model to dogvgg19.weights.best.mine.hdf5
0s - loss: 6.5903 - acc: 0.5840 - val_loss: 7.2848 - val_acc: 0.4790
Epoch 24/100
Epoch 00023: val_loss did not improve
0s - loss: 6.5369 - acc: 0.5907 - val_loss: 7.3219 - val_acc: 0.4719
Epoch 25/100
Epoch 00024: val_loss improved from 7.28480 to 7.25956, saving model to dogvgg19.weights.best.mine.hdf5
0s - loss: 6.4664 - acc: 0.5885 - val_loss: 7.2596 - val_acc: 0.4814
Epoch 26/100
Epoch 00025: val_loss improved from 7.25956 to 7.12388, saving model to dogvgg19.weights.best.mine.hdf5
1s - loss: 6.3779 - acc: 0.5942 - val_loss: 7.1239 - val_acc: 0.4802
Epoch 27/100
Epoch 00026: val_loss improved from 7.12388 to 7.10584, saving model to dogvgg19.weights.best.mine.hdf5
1s - loss: 6.2881 - acc: 0.5999 - val_loss: 7.1058 - val_acc: 0.4874
Epoch 28/100
Epoch 00027: val_loss improved from 7.10584 to 7.02109, saving model to dogvgg19.weights.best.mine.hdf5
0s - loss: 6.2545 - acc: 0.6057 - val_loss: 7.0211 - val_acc: 0.4946
Epoch 29/100
Epoch 00028: val_loss did not improve
1s - loss: 6.2443 - acc: 0.6084 - val_loss: 7.0366 - val_acc: 0.4934
Epoch 30/100
Epoch 00029: val_loss did not improve
1s - loss: 6.2331 - acc: 0.6108 - val_loss: 7.0892 - val_acc: 0.4970
Epoch 31/100
Epoch 00030: val_loss improved from 7.02109 to 6.99821, saving model to dogvgg19.weights.best.mine.hdf5
0s - loss: 6.2281 - acc: 0.6118 - val_loss: 6.9982 - val_acc: 0.4994
Epoch 32/100
Epoch 00031: val_loss did not improve
0s - loss: 6.2274 - acc: 0.6115 - val_loss: 7.0216 - val_acc: 0.4994
Epoch 33/100
Epoch 00032: val_loss did not improve
0s - loss: 6.2253 - acc: 0.6123 - val_loss: 7.0488 - val_acc: 0.5030
Epoch 34/100
Epoch 00033: val_loss did not improve
1s - loss: 6.2255 - acc: 0.6127 - val_loss: 7.0259 - val_acc: 0.5030
Epoch 35/100
Epoch 00034: val_loss did not improve
0s - loss: 6.2125 - acc: 0.6126 - val_loss: 7.0030 - val_acc: 0.5006
Epoch 36/100
Epoch 00035: val_loss did not improve
1s - loss: 6.1439 - acc: 0.6150 - val_loss: 7.1075 - val_acc: 0.4970
Epoch 37/100
Epoch 00036: val_loss improved from 6.99821 to 6.96425, saving model to dogvgg19.weights.best.mine.hdf5
0s - loss: 6.1254 - acc: 0.6180 - val_loss: 6.9643 - val_acc: 0.5018
Epoch 38/100
Epoch 00037: val_loss did not improve
0s - loss: 6.1237 - acc: 0.6186 - val_loss: 7.0201 - val_acc: 0.5006
Epoch 39/100
Epoch 00038: val_loss did not improve
0s - loss: 6.1219 - acc: 0.6193 - val_loss: 6.9773 - val_acc: 0.5030
Epoch 40/100
Epoch 00039: val_loss did not improve
0s - loss: 6.1235 - acc: 0.6192 - val_loss: 6.9847 - val_acc: 0.5042
Epoch 41/100
Epoch 00040: val_loss did not improve
0s - loss: 6.1215 - acc: 0.6196 - val_loss: 6.9831 - val_acc: 0.5066
Epoch 42/100
Epoch 00041: val_loss improved from 6.96425 to 6.91829, saving model to dogvgg19.weights.best.mine.hdf5
0s - loss: 6.1218 - acc: 0.6195 - val_loss: 6.9183 - val_acc: 0.5174
Epoch 43/100
Epoch 00042: val_loss did not improve
0s - loss: 6.1122 - acc: 0.6196 - val_loss: 7.1576 - val_acc: 0.4994
Epoch 44/100
Epoch 00043: val_loss did not improve
0s - loss: 5.9846 - acc: 0.6189 - val_loss: 6.9315 - val_acc: 0.5018
Epoch 45/100
Epoch 00044: val_loss improved from 6.91829 to 6.71216, saving model to dogvgg19.weights.best.mine.hdf5
0s - loss: 5.7268 - acc: 0.6290 - val_loss: 6.7122 - val_acc: 0.5138
Epoch 46/100
Epoch 00045: val_loss improved from 6.71216 to 6.64605, saving model to dogvgg19.weights.best.mine.hdf5
0s - loss: 5.5916 - acc: 0.6421 - val_loss: 6.6460 - val_acc: 0.5030
Epoch 47/100
Epoch 00046: val_loss improved from 6.64605 to 6.48516, saving model to dogvgg19.weights.best.mine.hdf5
0s - loss: 5.4434 - acc: 0.6463 - val_loss: 6.4852 - val_acc: 0.5222
Epoch 48/100
Epoch 00047: val_loss did not improve
0s - loss: 5.3546 - acc: 0.6597 - val_loss: 6.5194 - val_acc: 0.5269
Epoch 49/100
Epoch 00048: val_loss did not improve
0s - loss: 5.3319 - acc: 0.6633 - val_loss: 6.5013 - val_acc: 0.5269
Epoch 50/100
Epoch 00049: val_loss improved from 6.48516 to 6.40518, saving model to dogvgg19.weights.best.mine.hdf5
0s - loss: 5.2668 - acc: 0.6639 - val_loss: 6.4052 - val_acc: 0.5234
Epoch 51/100
Epoch 00050: val_loss improved from 6.40518 to 6.38941, saving model to dogvgg19.weights.best.mine.hdf5
0s - loss: 5.1440 - acc: 0.6731 - val_loss: 6.3894 - val_acc: 0.5257
Epoch 52/100
Epoch 00051: val_loss improved from 6.38941 to 6.25883, saving model to dogvgg19.weights.best.mine.hdf5
0s - loss: 5.0746 - acc: 0.6789 - val_loss: 6.2588 - val_acc: 0.5353
Epoch 53/100
Epoch 00052: val_loss improved from 6.25883 to 6.23667, saving model to dogvgg19.weights.best.mine.hdf5
0s - loss: 5.0642 - acc: 0.6822 - val_loss: 6.2367 - val_acc: 0.5341
Epoch 54/100
Epoch 00053: val_loss did not improve
0s - loss: 5.0480 - acc: 0.6826 - val_loss: 6.3109 - val_acc: 0.5425
Epoch 55/100
Epoch 00054: val_loss improved from 6.23667 to 6.19314, saving model to dogvgg19.weights.best.mine.hdf5
0s - loss: 4.9822 - acc: 0.6856 - val_loss: 6.1931 - val_acc: 0.5413
Epoch 56/100
Epoch 00055: val_loss did not improve
0s - loss: 4.9261 - acc: 0.6892 - val_loss: 6.2717 - val_acc: 0.5413
Epoch 57/100
Epoch 00056: val_loss improved from 6.19314 to 6.14829, saving model to dogvgg19.weights.best.mine.hdf5
0s - loss: 4.8963 - acc: 0.6915 - val_loss: 6.1483 - val_acc: 0.5401
Epoch 58/100
Epoch 00057: val_loss improved from 6.14829 to 6.02205, saving model to dogvgg19.weights.best.mine.hdf5
0s - loss: 4.8874 - acc: 0.6925 - val_loss: 6.0220 - val_acc: 0.5461
Epoch 59/100
Epoch 00058: val_loss did not improve
0s - loss: 4.8792 - acc: 0.6931 - val_loss: 6.0603 - val_acc: 0.5509
Epoch 60/100
Epoch 00059: val_loss did not improve
0s - loss: 4.8669 - acc: 0.6955 - val_loss: 6.0600 - val_acc: 0.5545
Epoch 61/100
Epoch 00060: val_loss did not improve
0s - loss: 4.8265 - acc: 0.6948 - val_loss: 6.1271 - val_acc: 0.5389
Epoch 62/100
Epoch 00061: val_loss improved from 6.02205 to 6.01439, saving model to dogvgg19.weights.best.mine.hdf5
0s - loss: 4.7964 - acc: 0.6976 - val_loss: 6.0144 - val_acc: 0.5593
Epoch 63/100
Epoch 00062: val_loss improved from 6.01439 to 5.98410, saving model to dogvgg19.weights.best.mine.hdf5
0s - loss: 4.7850 - acc: 0.6993 - val_loss: 5.9841 - val_acc: 0.5521
Epoch 64/100
Epoch 00063: val_loss did not improve
0s - loss: 4.7751 - acc: 0.7001 - val_loss: 6.0587 - val_acc: 0.5497
Epoch 65/100
Epoch 00064: val_loss did not improve
0s - loss: 4.7684 - acc: 0.7021 - val_loss: 6.0074 - val_acc: 0.5581
Epoch 66/100
Epoch 00065: val_loss did not improve
0s - loss: 4.7690 - acc: 0.7019 - val_loss: 5.9846 - val_acc: 0.5581
Epoch 67/100
Epoch 00066: val_loss improved from 5.98410 to 5.98298, saving model to dogvgg19.weights.best.mine.hdf5
0s - loss: 4.7638 - acc: 0.7028 - val_loss: 5.9830 - val_acc: 0.5521
Epoch 68/100
Epoch 00067: val_loss improved from 5.98298 to 5.97484, saving model to dogvgg19.weights.best.mine.hdf5
0s - loss: 4.7637 - acc: 0.7031 - val_loss: 5.9748 - val_acc: 0.5581
Epoch 69/100
Epoch 00068: val_loss improved from 5.97484 to 5.95822, saving model to dogvgg19.weights.best.mine.hdf5
0s - loss: 4.7626 - acc: 0.7037 - val_loss: 5.9582 - val_acc: 0.5653
Epoch 70/100
Epoch 00069: val_loss improved from 5.95822 to 5.92863, saving model to dogvgg19.weights.best.mine.hdf5
0s - loss: 4.7589 - acc: 0.7040 - val_loss: 5.9286 - val_acc: 0.5605
Epoch 71/100
Epoch 00070: val_loss improved from 5.92863 to 5.88064, saving model to dogvgg19.weights.best.mine.hdf5
0s - loss: 4.7641 - acc: 0.7037 - val_loss: 5.8806 - val_acc: 0.5701
Epoch 72/100
Epoch 00071: val_loss did not improve
0s - loss: 4.7603 - acc: 0.7039 - val_loss: 5.9363 - val_acc: 0.5629
Epoch 73/100
Epoch 00072: val_loss did not improve
0s - loss: 4.7615 - acc: 0.7037 - val_loss: 5.9506 - val_acc: 0.5713
Epoch 74/100
Epoch 00073: val_loss did not improve
0s - loss: 4.7618 - acc: 0.7036 - val_loss: 5.9151 - val_acc: 0.5713
Epoch 75/100
Epoch 00074: val_loss did not improve
0s - loss: 4.7597 - acc: 0.7045 - val_loss: 5.9533 - val_acc: 0.5557
Epoch 76/100
Epoch 00075: val_loss did not improve
0s - loss: 4.7599 - acc: 0.7043 - val_loss: 5.9636 - val_acc: 0.5725
Epoch 77/100
Epoch 00076: val_loss did not improve
0s - loss: 4.7605 - acc: 0.7042 - val_loss: 5.8966 - val_acc: 0.5784
Epoch 78/100
Epoch 00077: val_loss did not improve
0s - loss: 4.7617 - acc: 0.7039 - val_loss: 5.9351 - val_acc: 0.5677
Epoch 79/100
Epoch 00078: val_loss did not improve
0s - loss: 4.7607 - acc: 0.7039 - val_loss: 5.9668 - val_acc: 0.5653
Epoch 80/100
Epoch 00079: val_loss did not improve
0s - loss: 4.7606 - acc: 0.7042 - val_loss: 5.9270 - val_acc: 0.5689
Epoch 81/100
Epoch 00080: val_loss did not improve
0s - loss: 4.7620 - acc: 0.7040 - val_loss: 5.9529 - val_acc: 0.5677
Epoch 82/100
Epoch 00081: val_loss did not improve
0s - loss: 4.7629 - acc: 0.7040 - val_loss: 5.9572 - val_acc: 0.5772
Epoch 83/100
Epoch 00082: val_loss did not improve
0s - loss: 4.7618 - acc: 0.7040 - val_loss: 5.9580 - val_acc: 0.5689
Epoch 84/100
Epoch 00083: val_loss did not improve
0s - loss: 4.7620 - acc: 0.7042 - val_loss: 5.9670 - val_acc: 0.5641
Epoch 85/100
Epoch 00084: val_loss did not improve
0s - loss: 4.7595 - acc: 0.7042 - val_loss: 5.9973 - val_acc: 0.5713
Epoch 86/100
Epoch 00085: val_loss did not improve
0s - loss: 4.7618 - acc: 0.7042 - val_loss: 6.0239 - val_acc: 0.5689
Epoch 87/100
Epoch 00086: val_loss did not improve
0s - loss: 4.7600 - acc: 0.7040 - val_loss: 6.0208 - val_acc: 0.5629
Epoch 88/100
Epoch 00087: val_loss did not improve
0s - loss: 4.7623 - acc: 0.7039 - val_loss: 6.0153 - val_acc: 0.5593
Epoch 89/100
Epoch 00088: val_loss did not improve
0s - loss: 4.7612 - acc: 0.7039 - val_loss: 6.0401 - val_acc: 0.5677
Epoch 90/100
Epoch 00089: val_loss did not improve
0s - loss: 4.7616 - acc: 0.7039 - val_loss: 5.9861 - val_acc: 0.5796
Epoch 91/100
Epoch 00090: val_loss did not improve
0s - loss: 4.7612 - acc: 0.7040 - val_loss: 6.0392 - val_acc: 0.5653
Epoch 92/100
Epoch 00091: val_loss did not improve
0s - loss: 4.7592 - acc: 0.7043 - val_loss: 5.9963 - val_acc: 0.5689
Epoch 93/100
Epoch 00092: val_loss did not improve
0s - loss: 4.7602 - acc: 0.7037 - val_loss: 6.0102 - val_acc: 0.5689
Epoch 94/100
Epoch 00093: val_loss did not improve
0s - loss: 4.7611 - acc: 0.7039 - val_loss: 5.9979 - val_acc: 0.5665
Epoch 95/100
Epoch 00094: val_loss did not improve
0s - loss: 4.7602 - acc: 0.7042 - val_loss: 6.0130 - val_acc: 0.5677
Epoch 96/100
Epoch 00095: val_loss did not improve
0s - loss: 4.7581 - acc: 0.7043 - val_loss: 5.9981 - val_acc: 0.5725
Epoch 97/100
Epoch 00096: val_loss did not improve
0s - loss: 4.7599 - acc: 0.7040 - val_loss: 6.0032 - val_acc: 0.5689
Epoch 98/100
Epoch 00097: val_loss did not improve
0s - loss: 4.7617 - acc: 0.7039 - val_loss: 6.0110 - val_acc: 0.5701
Epoch 99/100
Epoch 00098: val_loss did not improve
0s - loss: 4.7607 - acc: 0.7040 - val_loss: 6.0216 - val_acc: 0.5665
Epoch 100/100
Epoch 00099: val_loss did not improve
0s - loss: 4.7617 - acc: 0.7040 - val_loss: 6.0050 - val_acc: 0.5713
In [27]:
### TODO: Train the model.

import keras
from keras.callbacks import ModelCheckpoint

checkpointer50 = ModelCheckpoint(filepath='dogresnet50.weights.best.mine.hdf5', verbose=1, save_best_only=True)

hist3 = ResNet50_model2.fit(train_ResNet50, train_targets, callbacks=[checkpointer50], epochs=10,
                       verbose=2, validation_data=(valid_ResNet50, valid_targets), shuffle=True)
Train on 6680 samples, validate on 835 samples
Epoch 1/10
Epoch 00000: val_loss improved from inf to 0.86192, saving model to dogresnet50.weights.best.mine.hdf5
2s - loss: 1.7539 - acc: 0.5825 - val_loss: 0.8619 - val_acc: 0.7533
Epoch 2/10
Epoch 00001: val_loss improved from 0.86192 to 0.67140, saving model to dogresnet50.weights.best.mine.hdf5
0s - loss: 0.4618 - acc: 0.8611 - val_loss: 0.6714 - val_acc: 0.7832
Epoch 3/10
Epoch 00002: val_loss improved from 0.67140 to 0.61037, saving model to dogresnet50.weights.best.mine.hdf5
0s - loss: 0.2626 - acc: 0.9166 - val_loss: 0.6104 - val_acc: 0.7988
Epoch 4/10
Epoch 00003: val_loss did not improve
0s - loss: 0.1586 - acc: 0.9548 - val_loss: 0.6561 - val_acc: 0.7988
Epoch 5/10
Epoch 00004: val_loss did not improve
0s - loss: 0.1057 - acc: 0.9704 - val_loss: 0.6124 - val_acc: 0.8060
Epoch 6/10
Epoch 00005: val_loss improved from 0.61037 to 0.59956, saving model to dogresnet50.weights.best.mine.hdf5
1s - loss: 0.0753 - acc: 0.9808 - val_loss: 0.5996 - val_acc: 0.8204
Epoch 7/10
Epoch 00006: val_loss did not improve
1s - loss: 0.0519 - acc: 0.9883 - val_loss: 0.6307 - val_acc: 0.8156
Epoch 8/10
Epoch 00007: val_loss did not improve
0s - loss: 0.0373 - acc: 0.9916 - val_loss: 0.6476 - val_acc: 0.8216
Epoch 9/10
Epoch 00008: val_loss did not improve
0s - loss: 0.0266 - acc: 0.9954 - val_loss: 0.7055 - val_acc: 0.8216
Epoch 10/10
Epoch 00009: val_loss did not improve
0s - loss: 0.0213 - acc: 0.9952 - val_loss: 0.6890 - val_acc: 0.8216
In [28]:
### TODO: Train the model.

import keras
from keras.callbacks import ModelCheckpoint

checkpointerInception = ModelCheckpoint(filepath='doginception.weights.best.mine.hdf5', verbose=1, save_best_only=True)

hist4 = Inception_model.fit(train_Inception, train_targets, callbacks=[checkpointerInception], epochs=10,
                       verbose=2, validation_data=(valid_Inception, valid_targets), shuffle=True)
Train on 6680 samples, validate on 835 samples
Epoch 1/10
Epoch 00000: val_loss improved from inf to 0.63370, saving model to doginception.weights.best.mine.hdf5
7s - loss: 1.2305 - acc: 0.6918 - val_loss: 0.6337 - val_acc: 0.7976
Epoch 2/10
Epoch 00001: val_loss improved from 0.63370 to 0.57641, saving model to doginception.weights.best.mine.hdf5
2s - loss: 0.4537 - acc: 0.8557 - val_loss: 0.5764 - val_acc: 0.8371
Epoch 3/10
Epoch 00002: val_loss did not improve
2s - loss: 0.3320 - acc: 0.8928 - val_loss: 0.6011 - val_acc: 0.8467
Epoch 4/10
Epoch 00003: val_loss did not improve
3s - loss: 0.2524 - acc: 0.9148 - val_loss: 0.6930 - val_acc: 0.8323
Epoch 5/10
Epoch 00004: val_loss did not improve
2s - loss: 0.2055 - acc: 0.9313 - val_loss: 0.6264 - val_acc: 0.8467
Epoch 6/10
Epoch 00005: val_loss did not improve
2s - loss: 0.1691 - acc: 0.9440 - val_loss: 0.6489 - val_acc: 0.8515
Epoch 7/10
Epoch 00006: val_loss did not improve
2s - loss: 0.1315 - acc: 0.9563 - val_loss: 0.6552 - val_acc: 0.8575
Epoch 8/10
Epoch 00007: val_loss did not improve
1s - loss: 0.1091 - acc: 0.9639 - val_loss: 0.6635 - val_acc: 0.8587
Epoch 9/10
Epoch 00008: val_loss did not improve
2s - loss: 0.0926 - acc: 0.9704 - val_loss: 0.6935 - val_acc: 0.8551
Epoch 10/10
Epoch 00009: val_loss did not improve
2s - loss: 0.0750 - acc: 0.9754 - val_loss: 0.7234 - val_acc: 0.8599
In [29]:
### TODO: Train the model.

import keras
from keras.callbacks import ModelCheckpoint

checkpointerXception = ModelCheckpoint(filepath='dogxception.weights.best.mine.hdf5', verbose=1, save_best_only=True)

hist5 = Xception_model.fit(train_Xception, train_targets, callbacks=[checkpointerXception], epochs=10,
                       verbose=2, validation_data=(valid_Xception, valid_targets), shuffle=True)
Train on 6680 samples, validate on 835 samples
Epoch 1/10
Epoch 00000: val_loss improved from inf to 0.55056, saving model to dogxception.weights.best.mine.hdf5
9s - loss: 1.1648 - acc: 0.7269 - val_loss: 0.5506 - val_acc: 0.8275
Epoch 2/10
Epoch 00001: val_loss improved from 0.55056 to 0.48223, saving model to dogxception.weights.best.mine.hdf5
4s - loss: 0.3940 - acc: 0.8757 - val_loss: 0.4822 - val_acc: 0.8359
Epoch 3/10
Epoch 00002: val_loss improved from 0.48223 to 0.46307, saving model to dogxception.weights.best.mine.hdf5
2s - loss: 0.3052 - acc: 0.9013 - val_loss: 0.4631 - val_acc: 0.8503
Epoch 4/10
Epoch 00003: val_loss did not improve
3s - loss: 0.2538 - acc: 0.9195 - val_loss: 0.4758 - val_acc: 0.8539
Epoch 5/10
Epoch 00004: val_loss did not improve
3s - loss: 0.2136 - acc: 0.9317 - val_loss: 0.4961 - val_acc: 0.8491
Epoch 6/10
Epoch 00005: val_loss did not improve
2s - loss: 0.1844 - acc: 0.9421 - val_loss: 0.4932 - val_acc: 0.8611
Epoch 7/10
Epoch 00006: val_loss did not improve
3s - loss: 0.1598 - acc: 0.9500 - val_loss: 0.5016 - val_acc: 0.8587
Epoch 8/10
Epoch 00007: val_loss did not improve
4s - loss: 0.1395 - acc: 0.9561 - val_loss: 0.5070 - val_acc: 0.8539
Epoch 9/10
Epoch 00008: val_loss did not improve
4s - loss: 0.1257 - acc: 0.9615 - val_loss: 0.5573 - val_acc: 0.8455
Epoch 10/10
Epoch 00009: val_loss did not improve
2s - loss: 0.1089 - acc: 0.9674 - val_loss: 0.5513 - val_acc: 0.8527

(IMPLEMENTATION) Load the Model with the Best Validation Loss

In [30]:
### TODO: Load the model weights with the best validation loss.
VGG19_model.load_weights('dogvgg19.weights.best.mine.hdf5')
In [31]:
### TODO: Load the model weights with the best validation loss.
ResNet50_model2.load_weights('dogresnet50.weights.best.mine.hdf5')
In [32]:
Inception_model.load_weights('doginception.weights.best.mine.hdf5')
In [33]:
Xception_model.load_weights('dogxception.weights.best.mine.hdf5')

(IMPLEMENTATION) Test the Model

Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 60%.

In [34]:
### TODO: Calculate classification accuracy on the test dataset.

print('Test accuracy: {0:.2f}%'.format(VGG19_model.evaluate(test_VGG19, test_targets)[1]*100))
832/836 [============================>.] - ETA: 0sTest accuracy: 57.42%
In [35]:
### TODO: Calculate classification accuracy on the test dataset.

print('Test accuracy with ResNet50 model: {0:.2f}%'.format(ResNet50_model2.evaluate(test_ResNet50, test_targets)[1]*100))
576/836 [===================>..........] - ETA: 0sTest accuracy with ResNet50 model: 81.82%
In [36]:
### TODO: Calculate classification accuracy on the test dataset.

print('Test accuracy with Inception model: {0:.2f}%'.format(Inception_model.evaluate(test_Inception, test_targets)[1]*100))
800/836 [===========================>..] - ETA: 0sTest accuracy with Inception model: 80.14%
In [37]:
### TODO: Calculate classification accuracy on the test dataset.

print('Test accuracy with Xception model: {0:.2f}%'.format(Xception_model.evaluate(test_Xception, test_targets)[1]*100))
800/836 [===========================>..] - ETA: 0sTest accuracy with Xception model: 85.05%

(IMPLEMENTATION) Predict Dog Breed with the Model

Write a function that takes an image path as input and returns the dog breed (Affenpinscher, Afghan_hound, etc) that is predicted by your model.

Similar to the analogous function in Step 5, your function should have three steps:

  1. Extract the bottleneck features corresponding to the chosen CNN model.
  2. Supply the bottleneck features as input to the model to return the predicted vector. Note that the argmax of this prediction vector gives the index of the predicted dog breed.
  3. Use the dog_names array defined in Step 0 of this notebook to return the corresponding breed.

The functions to extract the bottleneck features can be found in extract_bottleneck_features.py, and they have been imported in an earlier code cell. To obtain the bottleneck features corresponding to your chosen CNN architecture, you need to use the function

extract_{network}

where {network}, in the above filename, should be one of VGG19, Resnet50, InceptionV3, or Xception.

In [38]:
### TODO: Write a function that takes a path to an image as input
### and returns the dog breed that is predicted by the model.

from extract_bottleneck_features import extract_VGG19

def VGG19_predict_breed(img_path):
    bottleneck_img = extract_VGG19(path_to_tensor(img_path))
    predicted_vector = VGG19_model.predict(bottleneck_img)
    return dog_names[np.argmax(predicted_vector)]
In [39]:
### TODO: Write a function that takes a path to an image as input
### and returns the dog breed that is predicted by the model.

from extract_bottleneck_features import extract_Resnet50

def ResNet50_predict_breed(img_path):
    bottleneck_img = extract_Resnet50(path_to_tensor(img_path))
    predicted_vector = ResNet50_model2.predict(bottleneck_img)
    return dog_names[np.argmax(predicted_vector)]
In [40]:
### TODO: Write a function that takes a path to an image as input
### and returns the dog breed that is predicted by the model.

from extract_bottleneck_features import extract_InceptionV3

def Inception_predict_breed(img_path):
    bottleneck_img = extract_InceptionV3(path_to_tensor(img_path))
    predicted_vector = Inception_model.predict(bottleneck_img)
    return dog_names[np.argmax(predicted_vector)]
In [41]:
### TODO: Write a function that takes a path to an image as input
### and returns the dog breed that is predicted by the model.

from extract_bottleneck_features import extract_Xception

def Xception_predict_breed(img_path):
    bottleneck_img = extract_Xception(path_to_tensor(img_path))
    predicted_vector = Xception_model.predict(bottleneck_img)
    return dog_names[np.argmax(predicted_vector)]

Step 6: Write your Algorithm

Write an algorithm that accepts a file path to an image and first determines whether the image contains a human, dog, or neither. Then,

  • if a dog is detected in the image, return the predicted breed.
  • if a human is detected in the image, return the resembling dog breed.
  • if neither is detected in the image, provide output that indicates an error.

You are welcome to write your own functions for detecting humans and dogs in images, but feel free to use the face_detector and dog_detector functions developed above. You are required to use your CNN from Step 5 to predict dog breed.

Some sample output for our algorithm is provided below, but feel free to design your own user experience!

Sample Human Output

(IMPLEMENTATION) Write your Algorithm

In [42]:
# for i in range(100):
#     print(VGG19_predict_breed(human_files_short[i]))
In [43]:
def my_dog_detector(img_path, model):
    prediction = predict_labels(img_path, model)
    return ((prediction <= 268) & (prediction >= 151)) 

def predict_labels(img_path, model):
    # returns prediction vector for image located at img_path
    img = preprocess_input(path_to_tensor(img_path))
    return np.argmax(model.predict(img))
In [44]:
### TODO: Write your algorithm.
### Feel free to use as many code cells as needed.

def img_decetor(img_path):
    dog_breed = VGG19_predict_breed(img_path)
    if(dog_detector(img_path)):
        return 'Dog breed {}'.format(dog_breed)
    elif(face_detector(img_path)):
        return 'Human resembling {}'.format(dog_breed)
    else:
        return 'Neither human, nor dog'
    
In [45]:
### TODO: Write your algorithm.
### Feel free to use as many code cells as needed.

def img_decetor3(img_path):
    dog_breed = ResNet50_predict_breed(img_path)
    if(dog_detector(img_path)):
        return 'Dog breed {}'.format(dog_breed)
    elif(face_detector(img_path)):
        return 'Human resembling {}'.format(dog_breed)
    else:
        return 'Neither human, nor dog'
    
In [46]:
### TODO: Write your algorithm.
### Feel free to use as many code cells as needed.

def img_decetor4(img_path):
    dog_breed = Inception_predict_breed(img_path)
    if(dog_detector(img_path)):
        return 'Dog breed {}'.format(dog_breed)
    elif(face_detector(img_path)):
        return 'Human resembling {}'.format(dog_breed)
    else:
        return 'Neither human, nor dog'
    
In [47]:
### TODO: Write your algorithm.
### Feel free to use as many code cells as needed.

def img_decetor5(img_path):
    dog_breed = Xception_predict_breed(img_path)
    if(dog_detector(img_path)):
        return 'Dog breed {}'.format(dog_breed)
    elif(face_detector(img_path)):
        return 'Human resembling {}'.format(dog_breed)
    else:
        return 'Neither human, nor dog'
    

Step 7: Test Your Algorithm

In this section, you will take your new algorithm for a spin! What kind of dog does the algorithm think that you look like? If you have a dog, does it predict your dog's breed accurately? If you have a cat, does it mistakenly think that your cat is a dog?

(IMPLEMENTATION) Test Your Algorithm on Sample Images!

Test your algorithm at least six images on your computer. Feel free to use any images you like. Use at least two human and two dog images.

Question 6: Is the output better than you expected :) ? Or worse :( ? Provide at least three possible points of improvement for your algorithm.

Answer:

In [48]:
import pdb
In [56]:
## TODO: Execute your algorithm from Step 6 on
## at least 6 images on your computer.
## Feel free to use as many code cells as needed.

imgs = [
    "mytest/doberman-pinschers.png",
    "mytest/AfghanHound.jpg",
    "mytest/great-dane.jpg",
    "mytest/harsh.jpg",
    "mytest/roma.jpeg",
    "mytest/white-chihuahua.jpg",
    "mytest/doberman.jpg",
    "mytest/goldie.jpg",
    "mytest/bulldog.jpg",
    "mytest/yorkie.jpg"
    
]
In [59]:
import cv2

fig = plt.figure(figsize=(20,24))
for ind,img_path in enumerate(imgs):
    img = cv2.imread(img_path)
    cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    plt.subplot(5,2, ind+1)
    plt.imshow(cv_rgb)
#     pdb.set_trace()
    plt.title((img_decetor(img_path),img_path[7:]), 
               fontsize=(15))
In [58]:
#Try 3: with resnet

fig = plt.figure(figsize=(20,24))
for ind,img_path in enumerate(imgs):
    img = cv2.imread(img_path)
    cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    plt.subplot(5,2, ind+1)
    plt.imshow(cv_rgb)
    plt.title((img_decetor3(img_path),img_path[7:]), 
               fontsize=(15))
In [60]:
#Try 4: with inception

fig = plt.figure(figsize=(20,24))
for ind,img_path in enumerate(imgs):
    img = cv2.imread(img_path)
    cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    plt.subplot(5,2, ind+1)
    plt.imshow(cv_rgb)
    plt.title((img_decetor4(img_path),img_path[7:]), 
               fontsize=(15))
In [57]:
#Try 5: with xception

fig = plt.figure(figsize=(20,24))
for ind,img_path in enumerate(imgs):
    img = cv2.imread(img_path)
    cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    plt.subplot(5,2, ind+1)
    plt.imshow(cv_rgb)
    plt.title((img_decetor5(img_path),img_path[7:]), 
               fontsize=(15))

Answer: (Oh, now I get it.. was not reading the question i guess) I used a few more images to recognize the following possible points of improvemnt:

  1. The images with multiple dogs in it are difficult to recognize by any of the algorithms, as we do not have such images in our training data, so we can add more such images
  2. The images with the dog photos at different positions in the image give wrong results. 1 improvement would be to use the data augmentation and some translation invariance to improve prediction on such images
  3. The images with non-contrast backgrounds are not predicted by the algorithm correctly. Probably, we add more such images in the training dataset to achieve this

Answer: I tried multiple algorithms, and some of the output remains same:

  1. The images with multiple dogs in it are difficult to recognize by any of the algorithms, as we do not have such images in our training data

  2. Great dane, chihuahua and golden retriever are correctly identified by the algo

  3. Husky is not recognized as it was not included in the training dog images </ol> I am happy with the results given by the Xception algorithm

Answer: The output is not as I expected. I tried to use at least 4 different types of husky images, but the model couldnt recognize any.